package com.espressif.iot.ui.main;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.xiquezhijia.iot.R;
import com.espressif.iot.base.application.EspApplication;
import com.espressif.iot.type.user.EspLoginResult;
import com.espressif.iot.ui.main.LoginThirdPartyDialog.OnLoginListener;
import com.espressif.iot.ui.softap_sta_support.SoftApStaSupportActivity;
import com.espressif.iot.ui.softap_sta_support.help.HelpSoftApStaSupportActivity;
import com.espressif.iot.user.IEspUser;
import com.espressif.iot.user.builder.BEspUser;
import com.espressif.iot.util.EspStrings;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;

public class LoginActivity extends Activity implements OnClickListener
{
    private IEspUser mUser;
    
    private EditText mEmailEdt;
    private EditText mPasswordEdt;
    
    private CheckBox mAutoLoginCB;
    
    private Button mLoginBtn;
    private Button mRegisterBtn;
    private Button mLocalBtn;
    private Button mQuickUsageBtn;
    private TextView mThirdPartyLoginTV;
    
    private final static int REQUEST_REGISTER = 1;
    
    private LoginThirdPartyDialog mThirdPartyLoginDialog;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.login_activity);
        
        mUser = BEspUser.getBuilder().getInstance();
        
        init();
        

       
//        boolean result = Pattern.matches(XIQUEDEVICE_PATTERN_TYPE, teststring); 
//        result = teststring.matches(XIQUEDEVICE_PATTERN_TYPE);
//        Log.e("teststring", "espstring.matche(XIQUEDEVICE_PATTERN_TYPE)=" + espstring.matches(XIQUEDEVICE_PATTERN_TYPE));
//        Log.e("teststring", "gateway answer teststring.matche(XIQUEDEVICE_PATTERN_TYPE)=" + teststring.matches(XIQUEDEVICE_PATTERN_TYPE));
        
//     Pattern p = Pattern.compile("m(o+)n",Pattern.CASE_INSENSITIVE); 
//     // 用Pattern类的matcher()方法生成一个Matcher对象 
//     Matcher m = p.matcher("moon mooon Mon mooooon Mooon"); 
//     StringBuffer sb = new StringBuffer(); 
//     // 使用find()方法查找第一个匹配的对象 
//     boolean result = m.find(); 
//     // 使用循环找出模式匹配的内容替换之,再将内容加到sb里 
//     /* 根据模式用replacement替换相应内容,并将匹配的结果添加到sb当前位置之后
//      * */
//     while (result) { 
//    	 
//     m.appendReplacement(sb, "moon"); 
//     result = m.find(); 
//     } 
//     // 最后调用appendTail()方法将最后一次匹配后的剩余字符串加到sb里； 
//     m.appendTail(sb); 
     //System.out.println("替换后内容是" + sb.toString()); 
//        String input="职务=GM 薪水=50000 , 姓名=职业经理人 ; 性别=男 年龄=45 "; 
//        String patternStr="(\\s*,\\s*)|(\\s*;\\s*)|(\\s+)"; 
//        Pattern pattern=Pattern.compile(patternStr); 
//        String[] dataArr=pattern.split(input); 
//        for (String str : dataArr) { 
//        //System.out.println(str); 
//        Log.e("reg测试", str);
//        }   
        
        
//        String regex="<(\\w+)>(\\w+)</>"; 
//        Pattern pattern=Pattern.compile(regex); 
//        String input="<name>Bill</name><salary>50000</salary><title>GM</title>"; 
//        Matcher matcher=pattern.matcher(input); 
//        
//        while(matcher.find()){ 
//        //System.out.println(matcher.group(2)); 
//        Log.e("reg测试", matcher.group(1));
//        } 
        
//        regex="([a-zA-Z]+[0-9]+)"; 
//        pattern=Pattern.compile(regex); 
//        input="age45 salary500000 50000 title"; 
//        matcher=pattern.matcher(input); 
//        StringBuffer sb=new StringBuffer(); 
//        while(matcher.find()){ 
        	/* Returns the text that matched a given group of the regular 
        	 * expression. Explicit capturing groups 
        	 * in the pattern are numbered left to right in order of 
        	 * their opening parenthesis, starting at 1. 
        	 * The special group 0 represents the entire match 
        	 * (as if the entire pattern is surrounded 
        	 * by an implicit capturing group). For example, 
        	 * "a((b)c)" matching "abc" would give the following groups: 

			 0 "abc"
			 1 "bc"
			 2 "b"
 
			An optional capturing group that failed to match as part of 
			an overall successful match (for example, "a(b)?c" matching "ac") 
			returns null. A capturing group that matched the empty string 
			(for example, "a(b?)c" matching "ac") returns the empty string.
			
			Parameters
			group  the group, ranging from 0 to groupCount() - 1, with 0 
			representing the whole pattern. 
			
			Returns
			the text that matched the group. 

        	 * */
//        String replacement=matcher.group(1).toUpperCase(); 
//        Log.e("reg测试----", replacement);
//        /*根据模式用replacement替换相应内容,并将匹配的结果添加到sb当前位置之后
//         * */
//        matcher.appendReplacement(sb, replacement); 
//        } 
//        /* 将输入序列中匹配之后的末尾字串添加到sb当前位置之后.
//         * */
//        matcher.appendTail(sb); 
//        Log.e("reg测试", sb.toString()); 
    }
    
    private void init()
    {
        mEmailEdt = (EditText)findViewById(R.id.login_edt_account);
        mPasswordEdt = (EditText)findViewById(R.id.login_edt_password);
        
        mLoginBtn = (Button)findViewById(R.id.login_btn_login);
        mLoginBtn.setOnClickListener(this);
        
        mRegisterBtn = (Button)findViewById(R.id.login_btn_register);
        mRegisterBtn.setOnClickListener(this);
        
        mLocalBtn = (Button)findViewById(R.id.login_local);
        mLocalBtn.setOnClickListener(this);
        
        // listen the auto login event
        mAutoLoginCB = (CheckBox)findViewById(R.id.login_cb_auto_login);
        
        mQuickUsageBtn = (Button)findViewById(R.id.login_btn_quick_usage);
        mQuickUsageBtn.setOnClickListener(this);
        
        mThirdPartyLoginTV = (TextView)findViewById(R.id.login_text_third_party);
        mThirdPartyLoginTV.setOnClickListener(this);
        
        mThirdPartyLoginDialog = new LoginThirdPartyDialog(this);
        mThirdPartyLoginDialog.setOnLoginListener(mThirdPartyLoginListener);
    }
    
    @Override
    public void onClick(View v)
    {
        if (v == mLoginBtn)
        {
            login();
        }
        else if (v == mRegisterBtn)
        {
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivityForResult(intent, REQUEST_REGISTER);
        }
        else if (v ==  mLocalBtn)
        {
            Class<?> _class;
            if (EspApplication.HELP_ON)
            {
                _class = HelpSoftApStaSupportActivity.class;
            }
            else
            {
                _class = SoftApStaSupportActivity.class;
            }
            startActivity(new Intent(this, _class));
        }
        else if (v == mQuickUsageBtn)
        {
//            mUser.loadUserDeviceListDB();
//            Intent intent = new Intent(this, EspApplication.getEspUIActivity());
//            startActivity(intent);
        	Intent intent = new Intent(this, XqHomepage.class);
        	startActivity(intent);
            finish();
        }
        else if (v == mThirdPartyLoginTV)
        {
            mThirdPartyLoginDialog.show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQUEST_REGISTER)
        {
            if (resultCode == RESULT_OK)
            {
                String email = data.getStringExtra(EspStrings.Key.REGISTER_NAME_EMAIL);
                String password = data.getStringExtra(EspStrings.Key.REGISTER_NAME_PASSWORD);
                mEmailEdt.setText(email);
                mPasswordEdt.setText(password);
            }
        }
    }
    
    private void login()
    {
        String email = mEmailEdt.getText().toString();
        if (TextUtils.isEmpty(email))
        {
            Toast.makeText(this, R.string.esp_login_email_hint, Toast.LENGTH_SHORT).show();
            return;
        }
        String password = mPasswordEdt.getText().toString();
        if (TextUtils.isEmpty(password))
        {
            Toast.makeText(this, R.string.esp_login_password_hint, Toast.LENGTH_SHORT).show();
            return;
        }
        boolean autoLogin = mAutoLoginCB.isChecked();
        new LoginTask(this, email, password, autoLogin)
        {
            @Override
            public void loginResult(EspLoginResult result)
            {
                if (result == EspLoginResult.SUC)
                {
                    loginSuccess();
                }
            }
        }.execute();
    }
    
    private OnLoginListener mThirdPartyLoginListener = new OnLoginListener()
    {
        
        @Override
        public void onLoginComplete(EspLoginResult result)
        {
            if (result == EspLoginResult.SUC)
            {
                loginSuccess();
            }
        }
    };
    
    private void loginSuccess()
    {
        Intent intent = new Intent(this, EspApplication.getEspUIActivity());
        startActivity(intent);
        finish();
    }
}
